package m3;



import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.tomcat.jni.Local;

import java.util.Scanner;

public class Producer {
    public static void main(String[] args) throws Exception {
        //创建  事务生产者
        TransactionMQProducer p = new TransactionMQProducer("pro3");
        //设置name server地址
        p.setNamesrvAddr("192.168.64.141:9876");

        //设置 事务监听器
        p.setTransactionListener(new TransactionListener() {
            @Override //执行本地事务
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                System.out.println("执行业务："+message+o);
                if(Math.random()<0.5){
                    System.out.println("本地事务执行成功");
                    return LocalTransactionState.COMMIT_MESSAGE;
                }else {
                    System.out.println("本地事务执行失败");
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }

            }

            @Override //回查本地事务
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                System.out.println("服务器正在回查消息状态");


                return null;
            }
        });

        //启动
        p.start();
        //发送事务消息 while循环多次输入
        while(true){
            System.out.println("输入消息：");
            String s = new Scanner(System.in).nextLine();
            //新建消息对象
            Message msg = new Message("Topic3", s.getBytes());
            TransactionSendResult r = p.sendMessageInTransaction(msg, null);
            System.out.println("消息结果："+r);
            System.out.println("消息状态："+r.getLocalTransactionState());
        }
    }
}
